<template>
    <div>
        <el-row :gutter="20" class="toplink">
            <el-col :span="1.5">菜品分类</el-col>
            <el-col :span="6"><el-input v-model="searchName" placeholder="输入分类"></el-input></el-col>
        </el-row>
        <el-row :gutter="20" class="toplink">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="4">
                <el-button type="danger" icon="el-icon-remove-outline" 
                    :disabled="!multipleSelection.length"
                    @click="handleBatchDelete">删除</el-button>
            </el-col>
        </el-row>
        <div style="width: 1000px;">
            <el-table
                ref="multipleTable"
                :data="tableData"
                tooltip-effect="dark"
                :header-cell-style="{ background: '#faf3eb' }"
                @selection-change="handleSelectionChange">
                <el-table-column
                    type="selection"
                    width="100px">
                </el-table-column>
                <el-table-column
                    label="索引"
                    width="100px">
                    <template slot-scope="scope">{{ scope.row.id }}</template>
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="菜品分类"
                    width="400px">
                </el-table-column>
                <el-table-column
                    prop="address"
                    label="操作"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-view" @click="showDetail(scope.$index, scope.row)">详情</el-button>
                        <el-button size="mini" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="10"
                :page-sizes="[10]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                style="margin-top: 20px;">
            </el-pagination>

        </div>

        <!-- 修改详情/编辑对话框 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogVisible"
            width="30%">
            <el-descriptions :column="1" border v-if="!isEdit && !isAdd">
                <el-descriptions-item label="ID">{{ detailData.id }}</el-descriptions-item>
                <el-descriptions-item label="分类名称">{{ detailData.name }}</el-descriptions-item>
                <el-descriptions-item label="描述">{{ detailData.description || '暂无描述' }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">
                    {{ formatTime(detailData.createdAt) }}
                </el-descriptions-item>
                <el-descriptions-item label="更新时间">
                    {{ formatTime(detailData.updatedAt) }}
                </el-descriptions-item>
            </el-descriptions>
            <!-- 编辑/新增表单 -->
            <el-form :model="detailData" ref="form" v-else label-width="100px">
                <el-form-item 
                    label="分类名称" 
                    prop="name"
                    :rules="[{ required: true, message: '请输入分类名称', trigger: 'blur' }]">
                    <el-input v-model="detailData.name"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="detailData.description"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleSave" v-if="isEdit || isAdd">保 存</el-button>
                <el-button @click="dialogVisible = false" v-else>关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { getCategory, updateCategory, deleteCategory, addCategory } from '@/api/category'

export default {
    // eslint-disable-next-line vue/multi-word-component-names
    name: 'category',
    comments:{},
    data(){
        return{
            tableData: [],
            currentPage: 1,
            total: 0,
            searchName: '', // 搜索关键词
            isEdit: false, // 是否是编辑模式
            dialogVisible: false,
            detailData: {
                id: '',
                name: '',
                description: '',
                createdAt: '',
                updatedAt: ''
            },
            multipleSelection: [], // 多选数据
            isAdd: false, // 是否是新增模式
        }
    },
    computed: {
        // 动态计算对话框标题
        dialogTitle() {
            if (this.isAdd) return '新增分类'
            if (this.isEdit) return '编辑分类'
            return '分类详情'
        }
    },
    created() {
        // 页面创建时加载数据
        this.loadData()
    },
    methods: {
        // 加载数据的方法
        async loadData() {
            try {
                const name = this.searchName || 'all'
                const res = await getCategory(name, this.currentPage)
                if (res.data && res.status) {
                    this.tableData = res.data.records
                    this.total = res.data.total
                }
            } catch (error) {
                this.$message.error(`获取分类数据失败: ${error.message}`)
            }
        },
        // 搜索按钮点击事件
        handleSearch() {
            this.currentPage = 1 // 搜索时重置页码
            this.loadData()
        },
        // 页码改变事件
        handleCurrentChange(currentPage) {
            this.currentPage = currentPage
            this.loadData()
        },
        // 每页条数改变事件
        handleSizeChange(/* val */) {
            this.currentPage = 1
            this.loadData()
        },
        // 表格多选事件
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        // 新增按钮点击事件
        handleAdd() {
            this.isAdd = true
            this.isEdit = false
            this.detailData = {
                name: '',
                description: '',
                createdAt: '',
                updatedAt: ''
            }
            this.dialogVisible = true
        },
        // 编辑按钮点击事件
        handleEdit(index, row) {
            this.isAdd = false
            this.isEdit = true
            this.detailData = { ...row }
            this.dialogVisible = true
        },
        // 详情按钮点击事件
        showDetail(index, row) {
            this.isAdd = false
            this.isEdit = false
            this.detailData = { ...row }
            this.dialogVisible = true
        },
        // 删除按钮点击事件
        handleDelete(index, row) {
            this.$confirm('确认删除该分类吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    await deleteCategory(row.id)
                    this.$message.success('删除成功')
                    this.loadData()
                } catch (error) {
                    this.$message.error(`删除失败: ${error.message}`)
                }
            }).catch(() => {
                this.$message.info('已取消删除')
            })
        },
        // 格式化时间
        formatTime(time) {
            if (!time) return '暂无数据'
            try {
                const date = new Date(time)
                if (isNaN(date.getTime())) return '时间格式错误'
                return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
            } catch (error) {
                return '时间格式错误'
            }
        },
        // 保存编辑或新增
        async handleSave() {
            try {
                await this.$refs.form.validate()
                
                const now = new Date().toISOString()
                if (this.isAdd) {
                    const addData = {
                        ...this.detailData,
                        createdAt: now,
                        updatedAt: now
                    }
                    await addCategory(addData)
                    this.$message.success('新增成功')
                } else {
                    const updateData = {
                        ...this.detailData,
                        updatedAt: now
                    }
                    await updateCategory(updateData)
                    this.$message.success('更新成功')
                }
                this.dialogVisible = false
                this.loadData()
            } catch (error) {
                if (error === false) return // 表单验证失败
                this.$message.error(`保存失败: ${error.message}`)
            }
        },
        // 批量删除
        handleBatchDelete() {
            if (!this.multipleSelection.length) {
                this.$message.warning('请选择要删除的项目')
                return
            }

            this.$confirm(`确认删除选中的 ${this.multipleSelection.length} 项吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    await Promise.all(
                        this.multipleSelection.map(item => deleteCategory(item.id))
                    )
                    this.$message.success('批量删除成功')
                    this.loadData()
                } catch (error) {
                    this.$message.error(`批量删除失败: ${error.message}`)
                }
            }).catch(() => {
                this.$message.info('已取消删除')
            })
        }
    }
}
</script>
<style lang="less">
* {
    margin: 0;
    padding: 0;
}

.toplink{
    padding: 10px;
    line-height: 50px;
}

.el-descriptions {
    margin: 20px 0;
    .el-descriptions-item__label {
        width: 100px;
        text-align: right;
    }
}
</style>